from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from typing import List
from pydantic import BaseModel

# 存储 WebSocket 连接
connected_clients: List[WebSocket] = []

app = FastAPI()

# 配置 CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 定义导航项模型
class NavItem(BaseModel):
    label: str
    path: str

# 动态存储导航项数据
nav_items: List[NavItem] = [
    NavItem(label="首 页", path="/main"),
    NavItem(label="新 闻", path="/main/news"),
    NavItem(label="关 于", path="/main/about/mondstadt?cat=0"),
    NavItem(label="服 务", path="/main/services"),
    NavItem(label="产 品", path="/main/products"),
    NavItem(label="联系我们", path="/main/contact"),
]

@app.websocket("/ws/nav-items")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    connected_clients.append(websocket)
    try:
        # 初次连接时发送当前导航项数据
        await notify_clients()
        while True:
            await websocket.receive_text()  # 保持连接
    except WebSocketDisconnect:
        connected_clients.remove(websocket)

# 通知所有客户端
async def notify_clients():
    print("通知客户端，当前导航项数据:", nav_items)
    # 将 Pydantic 模型转换为字典列表
    serializable_nav_items = [item.dict() for item in nav_items]
    for client in connected_clients:
        try:
            await client.send_json(serializable_nav_items)  # 发送 JSON 格式数据
            print("已发送数据到客户端")
        except Exception as e:
            print(f"发送数据到客户端失败: {e}")

@app.post("/nav-items", response_model=NavItem)
async def add_nav_item(item: NavItem, background_tasks: BackgroundTasks):
    nav_items.append(item)
    background_tasks.add_task(notify_clients)
    return item

@app.get("/nav-items", response_model=List[NavItem])
async def get_nav_items():
    print("当前导航项数据:", nav_items)
    return nav_items